import json
import re
import redis

from django.shortcuts import render
from .models import *
from rest_framework.views import APIView
from rest_framework.response import Response
from .ser import *
from django.core.paginator import Paginator


# Create your views here.


class NewsM(APIView):
    def post(self, request):
        ser = NewsSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200})
        else:
            print(ser.errors)
            return Response({"code": 10010})

    def get(self, request):
        gain = News.objects.all()
        p = request.GET.get('page')
        page = Paginator(gain, 2)
        result = page.page(p)
        ser = NewsSer(result, many=True)
        return Response({'code': 200, 'matter': ser.data, 'tpages': page.num_pages})


class GgM(APIView):
    def post(self, request):
        gain = Ggser(data=request.data)
        if gain.is_valid():
            gain.save()
            return Response({'code': 200})
        return Response({'code': 10010})

    def get(self, request):
        gain = Gg.objects.all()
        p = request.GET.get('p')
        page = Paginator(gain, 2)
        result = page.page(p)
        ser = Ggser(result, many=True)
        return Response({'code': 200, 'matter': ser.data, 'tpages':page.num_pages})




# class Text(APIView):
#     def get(self, request):
#         accId = '8aaf07087a331dc7017ae5ce36e83649'
#         accToken = '5ea139cb96174d499534494e9489904c'
#         appId = '8aaf07087a331dc7017ae5ce37be3650'
#         sdk = SmsSDK(accId, accToken, appId)
#         tid = '1'
#         datas = (236236, 1)
#         resp = sdk.sendMessage(tid, 13289792767, datas)
#         result = json.loads(resp)
#         if result['statusCode'] == '000000':
#             return 1
#         return 2
#
#
# class Register(APIView):
#     def post(self, request):
#         # 验证用户名是否为空
#         username = request.data.get('username')
#         if not username:
#             return Response({'code': 10010})
#         # 格式是否正确
#         name = re.match('\w{5,10}$', username)
#         if not name:
#             return Response({'code': 10011})
#         # 是否唯一
#         user = User.objects.first(username=username).first()
#         if user:
#             return Response({'code': 10012})
#
#         # 手机号
#         mobile = request.data.get('mobile')
#         if not mobile:
#             return Response({'code': 10013})
#         mobile = re.match('/^1[3-9]d{9}$/', mobile)
#         if not mobile:
#             return Response({'code': 10014})
#         # 是否唯一
#         mobile = User.objects.first(mobile=mobile).first()
#         if mobile:
#             return Response({'code': 10015})
#
#         return Response({'code': 200})
#
#
#
# from ronglian_sms_sdk import SmsSDK
# accId = '8a216da878005a800178a251439d39da'
# accToken = 'dc4fd2e2a23e45a68474dbc6d1233eda'
# appId = '8a216da878005a800178a251449839e1'
# import json
# def send_message(mobile,code,time):
#     sdk = SmsSDK(accId, accToken, appId)
#     tid = '1'
#     datas = (code, time)
#     resp = sdk.sendMessage(tid, mobile, datas)
#     result = json.loads(resp)
#     if result['statusCode'] == '000000':
#         return 1
#     return 2
#
#
# from utils.comm import send_message
# import random
# class SendSms(APIView):
#     def post(self,request):
#         mobile = request.data.get('mobile')
#         code = random.randint(100000,999999)
#         res = send_message(mobile,str(code),1)
#         code = 10010
#         if res:
#             code = 200
#         return Response({"code":code})
#
# import random, re
# from rest_framework.response import Response
# from rest_framework.views import APIView
# from utils.comm import send_message, get_redis
# from users.models import *


# 测试
class Text(APIView):
    def get(self, request):
        conn = get_redis()
        conn.setex('username', 10, 'xiaoming236')
        name = conn.get('username')
        return Response(name)


# 注册
class Register(APIView):
    def post(self, request):

        # 用户名
        username = request.data.get('username')
        if not username:
            return Response({'code': 10010})
        # 格式是否正确
        name = re.match('\w{5,10}$', username)
        if not name:
            return Response({'code': 10011})
        # 是否唯一
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code': 10012})

        # 密码
        password = request.data.get('password')
        if not password:
            return Response({'code': 10013})
        # 格式是否正确
        pwd = re.match('\w{3,6}$', password)
        if not pwd:
            return Response({'code': 10014})

        # 手机号
        mobile = request.data.get('mobile')
        if not mobile:
            return Response({'code': 10016})
        phone = re.match('^1[3-9]\d{9}$', mobile)
        if not phone:
            return Response({'code': 10017})
        # 是否唯一
        sloe = User.objects.filter(mobile=mobile).first()
        if sloe:
            return Response({'code': 10018})

        # 验证码验证
        smscode = request.data.get('smscode')
        conn = get_redis()
        code = conn.get(mobile)
        if code:
            code = str(code, encoding='utf8')
        if smscode != code:
            return Response({'code': 10019})

        return Response({'code': 200, 'meg': '注册成功'})


# 验证码
class SendSms(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        codesms = random.randint(1000, 9999)
        res = send_message(mobile, str(codesms), 1)
        code = 10010
        if res:
            code = 200
            # 发生成功后存入redis
            conn = get_redis()
            conn.setex(mobile, 60, codesms)
        return Response({'code': code})


class Home(APIView):
    def get(self, request):
        # 读取一级
        cates = Category.objects.filter(parent_id__isnull=True).all()
        list = []
        for i in cates:
            dict = {}
            dict['id'] = i.id
            dict['name'] = i.name
            # 读取二级
            two = i.subs.all()
            twolist = []
            # 遍历二级获取三级
            for j in two:
                twodict = {}
                twodict['id'] = j.id
                twodict['name'] = j.name
                three = j.subs.all()
                ser = CateSer(three, many=True)
                twodict['subs'] = ser.data
                twolist.append(twodict)

            dict['subs'] = twolist
            list.append(dict)

        return Response({"code": 200, 'catelist': list})

#购物车表
class Cart(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    goods = models.ForeignKey(Goods,on_delete=models.CASCADE)
    number = models.IntegerField(default=1)
    is_checked= models.BooleanField(default=True)

    class Meta:
        db_table='cart'


class CartM(APIView):
    def post(self,request):
        #判断此用户是否购买过此商品
        userid = request.data.get('user')
        goodsid = request.data.get('goods')
        number = int(request.data.get('number'))
        cart = Cart.objects.filter(user_id=userid,goods=goodsid).first()
        if cart:
        #如果买过数量+
            cart.number +=number
            cart.save()
            return Response({"code":200})
        else:
        #没买过购物车新增一条记录
            ser = CartSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({"code":200})
            else:
                print(ser.errors)
                return Response({"code":10010})


import json


class Buy(APIView):
    def post(self, request):
        userid = request.data.get('userid')
        goods_id = request.data.get('goods_id')
        conn = get_redis()
        key = 'cart_' + userid
        cart = conn.hget(key, goods_id)
        if cart:
            conn.hincrby(key, goods_id, 1)
        else:
            conn.hset('cart_' + userid, goods_id, 1)
        return Response('ok')

    def get(self, request):
        userid = request.GET.get('userid')
        conn = get_redis()
        key = 'cart_' + str(userid)
        carts = conn.hgetall(key)
        data = ''
        list = []
        sum = 0
        tmoney = 0
        t_count = 0
        selected_all = True
        if carts:

            selectedlist = conn.smembers('select_cart_%userid' % int(userid))

            for k, v in carts.items():
                sum += int(v)
                goods = Goods.objects.filter(id=k).first()

                dict = {}
                dict['id'] = goods.id
                dict['name'] = goods.name
                dict['price'] = goods.price
                dict['image'] = 'http://localhost:8000/upload/' + str(goods.pic)
                dict['count'] = v
                if k in selectedlist:
                    tmoney += int(v) * goods.price
                    dict['selected'] = True
                    t_count += int(v)
                else:
                    dict['selected'] = False
                    selected_all = False
                list.append(dict)

        return Response({"code": 200, 'carts': list, 'total': sum, 'tmoney': tmoney, 't_count': t_count,
                         'selected_all': selected_all})

    class SelectAll1(APIView):
        def get(self, request):
            conn = get_redis()
            selected = request.GET.get('selected')
            userid = request.GET.get('userid')
            key = 'cart_' + str(userid)
            carts = conn.hgetall(key)

            if selected == 'false':
                conn.srem('select_cart_%userid' % int(userid), *carts.keys())
            else:
                conn.sadd('select_cart_%userid' % int(userid), *carts.keys())
            return Response({'code': 200})

        def post(self, request):
            conn = get_redis()
            selected = request.data.get('flag')
            userid = request.data.get('userid')
            id = request.data.get('id')

            key = 'cart_' + str(userid)
            carts = conn.hgetall(key)
            print(selected)
            if selected == False:
                conn.srem('select_cart_%userid' % int(userid), id)
            else:
                conn.sadd('select_cart_%userid' % int(userid), id)
            return Response({'code': 200})

        def put(self, request):
            conn = get_redis()
            userid = request.data.get('userid')
            id = request.data.get('id')
            type = request.data.get('type')
            key = 'cart_' + str(userid)
            if type == 1:
                conn.hincrby(key, id, 1)
            elif type == 2:
                count = conn.hget(key, id)
                if int(count) > 1:
                    conn.hincrby(key, id, -1)
                else:
                    return Response({'code': 400})
            elif type == 3:
                count = int(request.data.get('count'))
                if count > 0:
                    conn.hset(key, id, count)
                else:
                    return Response({'code': 400})
            return Response({'code': 200})

        # 删除
        def delete(self, request):
            conn = get_redis()
            userid = request.GET.get('userid')
            id = request.GET.get('id')
            print(userid)
            print(id)
            conn.hdel('cart_' + str(userid), id)
            return Response({'code': 200})

        class AddViewHistory(APIView):
            def post(self, request):
                userid = request.data.get('userid')
                goodsid = request.data.get('goodsid')
                key = 'history_%userid' % int(userid)
                conn = get_redis()
                # 先去重
                conn.lrem(key, 0, goodsid)
                # 添加
                conn.lpush(key, goodsid)
                # 截取
                data = conn.ltrim(key, 0, 1)

                history = conn.lrange(key, 0, -1)
                list = []
                for i in history:
                    goods = Goods.objects.filter(id=i).first()
                    ser = GoodsSer(goods)
                    list.append(ser.data)
                return Response({'code': 200, 'list': list})

# 测试
class Text(APIView):
    def get(self, request):
        conn = get_redis()
        conn.setex('username', 10, 'xiaoming236')
        name = conn.get('username')
        return Response(name)


# 注册
class Register(APIView):
    def post(self, request):

        # 用户名
        username = request.data.get('username')
        if not username:
            return Response({'code': 10010})
        # 格式是否正确
        name = re.match('\w{5,10}$', username)
        if not name:
            return Response({'code': 10011})
        # 是否唯一
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code': 10012})

        # 密码
        password = request.data.get('password')
        if not password:
            return Response({'code': 10013})
        # 格式是否正确
        pwd = re.match('\w{3,6}$', password)
        if not pwd:
            return Response({'code': 10014})

        # 手机号
        mobile = request.data.get('mobile')
        if not mobile:
            return Response({'code': 10016})
        phone = re.match('^1[3-9]\d{9}$', mobile)
        if not phone:
            return Response({'code': 10017})
        # 是否唯一
        sloe = User.objects.filter(mobile=mobile).first()
        if sloe:
            return Response({'code': 10018})

        # 验证码验证
        smscode = request.data.get('smscode')
        conn = get_redis()
        code = conn.get(mobile)
        if code:
            code = str(code, encoding='utf8')
        if smscode != code:
            return Response({'code': 10019})

        return Response({'code': 200, 'meg': '注册成功'})


# 验证码
class SendSms(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        # 验证图片验证码,通过后发短信
        uid = request.data.get('uid')
        imagecode = request.data.get('imagecode')
        conn = get_redis()
        imgcode = conn.get(uid)
        if imgcode:
            imgcode = str(imgcode, encoding='utf8')
            if imagecode.lower() == imgcode.lower():
                codesms = random.randint(1000, 9999)
                res = send_message(mobile, str(codesms), 1)
                if res:
                    # 发生成功后存入redis
                    conn = get_redis()
                    conn.setex(mobile, 60, codesms)
                    # 判断是否同意协议
                    agree = request.data.get('agree')
                    if not agree:
                        return Response({'code': 10020})
                    # 注册功能
                    request.data['password'] = make_password(request.data.get('password'))
                    ser = UserModel(data=request.data)
                    if ser.is_valid():
                        ser.save()
                        return Response({'code': 200})
                    return Response({'code': 10021})


# 生成图片验证码
from utils.captcha.captcha import captcha


class CreateCaptcha(APIView):
    def get(self, request):
        uuid = request.GET.get('uuid')
        name, text, img = captcha.generate_captcha()
        # redis存储
        conn = get_redis()
        conn.set(uuid, text)
        return HttpResponse(img, content_type='image/jpg')


# 添加地址
class AddressM(APIView):
    def post(self, request):
        ser = AddressModel(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})

    def get(self, request):
        userid = request.GET.get('userid')
        address = Address.objects.filter(user_id=userid).all()
        ser = AddressModel(address, many=True)
        return Response({'code': 200, 'list': ser.data})

    def put(self, request):
        # 获取id
        id = request.GET.get('id')
        # 通过id查询
        address = Address.objects.filter(id=id).first()
        # 根据userid和is_default=1更新is_default=0
        Address.objects.filter(user_id=address.user_id, is_default=1).update(is_default=0)
        # 把当前id设置成默认5
        address.is_default = 1
        address.save()
        return Response({"code": 200})


# 首页展示
def xTree(datas):
    list = []
    tree = {}
    for i in datas:
        tree[i['id']] = i

    for i in datas:
        parent = i['parent']
        if not parent:
            list.append(i)
        else:
            if 'son' not in tree[parent]:
                tree[parent]['son'] = []
            tree[parent]['son'].append(i)
    return list


# 读取首页三级分类
class Home(APIView):
    def get(self, request):
        # 读取一级
        cates = Category.objects.filter(parent_id__isnull=True).all()
        list = []
        for i in cates:
            dict = {}
            dict['id'] = i.id
            dict['name'] = i.name
            # 读取二级
            two = i.subs.all()
            twolist = []
            # 遍历二级获取三级
            for j in two:
                twodict = {}
                twodict['id'] = j.id
                twodict['name'] = j.name
                three = j.subs.all()
                ser = CateSer(three, many=True)
                twodict['subs'] = ser.data
                twolist.append(twodict)

                dict['subs'] = twolist
                list.append(dict)
                categoods = []
                for j in cates:
                    dict = {}
                    dict['id'] = j.id
                    dict['name'] = j.name
                    dict['pic'] = str(j.pic)
                    two = j.subs.all()
                    twoser = CateSer(two, many=True)
                    dict['two'] = twoser.data
                    # 获取三级
                    three = Category.objects.filter(top_parent=j.id, level=3).all()
                    threeser = CateSer(three, many=True)
                    dict['three'] = threeser.data
                    # 获取商品,排序，新品按时间倒序排，价格，销量
                    sorted = request.GET.get('sorted')
                    topid = request.GET.get('topid')

                    goods = Goods.objects.filter(category1_id=j.id, home_show=1).all()
                    if sorted:
                        if int(topid) == int(j.id):
                            goods = Goods.objects.filter(category1_id=j.id, home_show=1).order_by('-' + sorted).all()

                    gser = GoodsSer(goods, many=True)
                    dict['goods'] = gser.data
                    categoods.append(dict)
                return Response({"code": 200, 'catelist': list, 'categoods': categoods})


#  商品详情页
class GoodsM(APIView):
    def get(self, request):
        id = request.GET.get('id')
        good = Goods.objects.filter(id=id).first()
        ser = GoodsSer(good)
        return Response({"code": 200, 'good': ser.data})


class CartM(APIView):
    def post(self, request):
        userid = request.data.get('user')
        goodsid = request.data.get('goods')
        number = request.data.get('number')
        cart = Cart.objects.filter(user_id=userid, goods_id=goodsid).first()
        if cart:
            cart.number += number
            cart.save()
            return Response({'code': 200})
        else:
            ser = CateSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'code': 200})
            else:
                print(ser.errors)
                return Response({'code': 10010})

    def get(self, request):
        userid = request.data.get('userid')
        cart = Cart.objects.filter(user_id=userid).all()
        ser = CateSer(cart, many=True)
        return Response({'code': 200, 'list': ser.data})

# from django.http import HttpResponse
# from utils.captcha.captcha import captcha
# class CreateCaptcha(APIView):
#     def get(self,request):
#         name,text,img=captcha.generate_captcha()
#         return HttpResponse(img,content_type='image/jpg')